const dataList = document.getElementById('data-list');

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function () {
    // 获取URL参数
    const urlParams = new URLSearchParams(window.location.search);
    const contentType = urlParams.get('type');

    // 菜单功能初始化 - 扩展公共菜单功能，添加特定的页面跳转逻辑
    const menuItems = document.querySelectorAll('.menu-item');

    // 二级菜单点击事件处理
    const submenuItems = document.querySelectorAll('.submenu-item');
    submenuItems.forEach(item => {
        item.addEventListener('click', function (e) {
            e.stopPropagation();

            // 获取submenu类型
            const submenuType = this.getAttribute('data-submenu');

            // 根据submenu类型设置跳转URL
            let targetUrl = '';
            if (submenuType === 'status1') {
                targetUrl = '../work-status/index.html?type=exhibition';
            } else if (submenuType === 'statu2') {
                targetUrl = '../work-status/index.html?type=inquiry';
            } else if (submenuType === 'service4') {
                targetUrl = '../public-service/index.html?type=exhibition';
            } else if (submenuType === 'service5') {
                targetUrl = '../public-service/index.html?type=inquiry';
            } else if (submenuType === 'service1') {
                targetUrl = '../public-service/index.html?type=reservation';
            } else if (submenuType === 'service2') {
                targetUrl = '../public-service/index.html?type=message';
            } else if (submenuType === 'service3') {
                targetUrl = '../public-service/index.html?type=donation';
            } else if (submenuType === 'overview1') {
                targetUrl = '../archival-collections/index.html?type=inquiry';
            } else if (submenuType === 'overview2') {
                targetUrl = '../archival-collections/index.html?type=exhibition';
            } else if (submenuType === 'culture1') {
                targetUrl = '../chronicle-culture/index.html?type=exhibition';
            } else if (submenuType === 'culture2') {
                targetUrl = '../chronicle-culture/index.html?type=inquiry';
            } else if (submenuType === 'culture3') {
                targetUrl = '../chronicle-culture/index.html?type=culture';
            }

            // 跳转到对应页面
            if (targetUrl) {
                window.location.href = targetUrl;
            }
        });
    });

    menuItems.forEach(item => {
        // 保存原始的点击事件处理函数
        const originalClickHandler = item.onclick;

        // 添加自定义点击事件处理函数
        item.addEventListener('click', function (e) {
            // 特殊菜单处理
            const menuType = this.getAttribute('data-menu');
            if (menuType === 'home') {
                window.location.href = '../home/index.html';
                return;
            } else if (menuType === 'status') {
                // 已经在工作动态页面，不需要跳转
                return;
            } else if (menuType === 'notices') {
                window.location.href = '../notice-announcement/index.html';
                return;
            } else if (menuType === 'services') {
                window.location.href = '../public-service/index.html';
                return;
            } else if (menuType === 'overview') {
                window.location.href = '../archival-collections/index.html';
                return;
            } else if (menuType === 'culture') {
                window.location.href = '../chronicle-culture/index.html';
                return;
            }
        });
    });

    // 全局数据和状态
    let exhibitionData = []; // 馆办动态数据
    let inquiryData = []; // 业内动态数据
    let currentData = []; // 当前显示的数据
    let currentPage = 1; // 当前页码
    let pageSize = 10; // 每页显示数量
    let totalPages = 1; // 总页数
    let currentDataType = 'exhibition'; // 当前显示的数据类型

    // 生成馆办动态数据
    function generateExhibitionData() {
        const titles = [
            '朝阳区档案馆开展{year}年度档案业务培训',
            '朝阳区档案信息化建设项目顺利通过验收',
            '朝阳区档案馆举办"铭记历史 砥砺前行"主题展览',
            '朝阳区完成{year}年度文件材料归档工作检查',
            '朝阳区地方志编纂工作取得新进展',
            '朝阳区召开档案工作联席会议 统筹推进全区档案事业发展',
            '朝阳区档案馆新馆建设项目获区政府重点支持',
            '朝阳区"十四五"档案事业发展规划实施情况评估会召开',
            '朝阳区领导调研区档案馆工作 强调做好存史资政育人',
            '朝阳区召开区委常委会会议 研究部署档案工作'
        ];

        const data = [];
        const currentYear = new Date().getFullYear();

        for (let i = 0; i < 300; i++) {
            const titleTemplate = titles[i % titles.length];
            const year = currentYear - Math.floor(i / 100);
            const title = titleTemplate.replace('{year}', year);

            // 生成日期：从当前日期往前推，保证日期唯一
            const date = new Date();
            date.setDate(date.getDate() - i - Math.floor(Math.random() * 30));
            const yearStr = date.getFullYear();
            const monthStr = String(date.getMonth() + 1).padStart(2, '0');
            const dayStr = String(date.getDate()).padStart(2, '0');
            const dateStr = `${yearStr}-${monthStr}-${dayStr}`;

            data.push({
                id: i + 1,
                title: title,
                date: dateStr
            });
        }

        return data.sort((a, b) => new Date(b.date) - new Date(a.date));
    }

    // 生成业内动态数据
    function generateInquiryData() {
        const titles = [
            '国家档案局关于加强{year}年档案安全工作的通知',
            '北京市档案局举办全市档案系统先进经验交流会',
            '全国档案工作会议在京召开 部署{year}年重点任务',
            '《北京市档案条例》修订工作启动',
            '数字档案馆建设国家标准发布实施',
            '全国档案信息化建设现场推进会召开',
            '国家档案局公布第五批中国档案文献遗产名录',
            '北京市档案馆举办"红色档案 百年记忆"主题展览',
            '档案专业人员职称评审工作开始申报',
            '全国档案科技成果推广应用交流会召开'
        ];

        const data = [];
        const currentYear = new Date().getFullYear();

        for (let i = 0; i < 300; i++) {
            const titleTemplate = titles[i % titles.length];
            const year = currentYear - Math.floor(i / 100);
            const title = titleTemplate.replace('{year}', year);

            // 生成日期：从当前日期往前推，保证日期唯一
            const date = new Date();
            date.setDate(date.getDate() - i - Math.floor(Math.random() * 30));
            const yearStr = date.getFullYear();
            const monthStr = String(date.getMonth() + 1).padStart(2, '0');
            const dayStr = String(date.getDate()).padStart(2, '0');
            const dateStr = `${yearStr}-${monthStr}-${dayStr}`;

            data.push({
                id: i + 1,
                title: title,
                date: dateStr
            });
        }

        return data.sort((a, b) => new Date(b.date) - new Date(a.date));
    }

    // 渲染数据列表
    function renderList(data) {
        const dynamicList = document.querySelector('.dynamic-list');
        dynamicList.innerHTML = '';

        data.forEach(item => {
            const li = document.createElement('li');
            li.className = 'dynamic-item';
            li.innerHTML = `
                <div class="title">${item.title}</div>
                <div class="date">${item.date}</div>
            `;

            // 添加点击事件
            li.addEventListener('click', function () {
                alert('您点击了：' + item.title);
            });

            dynamicList.appendChild(li);
        });
    }

    // 渲染分页信息
    function renderPagination() {
        const pageInfo = document.querySelector('#page-info');
        let pageNumbers = '';

        // 始终显示第一页
        if (currentPage === 1) {
            pageNumbers += '<span class="current page-item">1</span>';
        } else {
            pageNumbers += '<span class="page-item" onclick="goToPage(1)">1</span>';
        }

        // 如果当前页大于4，显示省略号
        if (currentPage > 4) {
            pageNumbers += '<span class="slide">...</span>';
        }

        // 显示当前页前后各两页
        let start = Math.max(2, currentPage - 2);
        let end = Math.min(totalPages - 1, currentPage + 2);

        for (let i = start; i <= end; i++) {
            if (i === currentPage) {
                pageNumbers += `<span class="current page-item">${i}</span>`;
            } else {
                pageNumbers += `<span class="page-item" onclick="goToPage(${i})">${i}</span>`;
            }
        }

        // 如果当前页小于总页数-3，显示省略号
        if (currentPage < totalPages - 3) {
            pageNumbers += '<span class="slide">...</span>';
        }

        // 始终显示最后一页
        if (totalPages > 1) {
            if (currentPage === totalPages) {
                pageNumbers += `<span class="current page-item">${totalPages}</span>`;
            } else {
                pageNumbers += `<span class="page-item" onclick="goToPage(${totalPages})">${totalPages}</span>`;
            }
        }

        pageInfo.innerHTML = pageNumbers;

        // 更新上一页、下一页按钮状态和样式
        const prevBtn = document.querySelector('#prev-page');
        const nextBtn = document.querySelector('#next-page');
        prevBtn.disabled = currentPage <= 1;
        nextBtn.disabled = currentPage >= totalPages;

        // 为禁用状态的按钮添加样式
        if (prevBtn.disabled) {
            prevBtn.style.backgroundColor = '#f9f9f9';
            prevBtn.style.cursor = 'not-allowed';
        } else {
            prevBtn.style.backgroundColor = '';
            prevBtn.style.cursor = '';
        }

        if (nextBtn.disabled) {
            nextBtn.style.backgroundColor = '#f9f9f9';
            nextBtn.style.cursor = 'not-allowed';
        } else {
            nextBtn.style.backgroundColor = '';
            nextBtn.style.cursor = '';
        }

        // 更新页码输入框
        const pageInput = document.querySelector('#page-input');
        pageInput.value = currentPage;
    }

    // 在全局作用域中定义goToPage函数，使其在HTML中可访问
    window.goToPage = function (page) {
        if (page >= 1 && page <= totalPages) {
            currentPage = page;

            // 计算当前页显示的数据
            const startIndex = (currentPage - 1) * pageSize;
            const endIndex = Math.min(startIndex + pageSize, currentData.length);
            const pageData = currentData.slice(startIndex, endIndex);

            // 重新渲染列表和分页
            renderList(pageData);
            renderPagination();
        }
    };

    // 切换页码
    function changePage(page) {
        if (page < 1 || page > totalPages) {
            return;
        }

        currentPage = page;

        // 计算当前页显示的数据
        const startIndex = (currentPage - 1) * pageSize;
        const endIndex = Math.min(startIndex + pageSize, currentData.length);
        const pageData = currentData.slice(startIndex, endIndex);

        // 重新渲染列表和分页
        renderList(pageData);
        renderPagination();
    }

    // 切换每页显示数量
    function changePageSize(size) {
        pageSize = parseInt(size);
        currentPage = 1;

        // 重新计算总页数
        totalPages = Math.ceil(currentData.length / pageSize);

        // 重新渲染列表和分页
        changePage(1);
    }

    // 初始化数据
    exhibitionData = generateExhibitionData();
    inquiryData = generateInquiryData();
    currentData = exhibitionData;
    totalPages = Math.ceil(currentData.length / pageSize);

    // 初始渲染
    changePage(1);

    // 左侧树形菜单功能初始化
    const treeItems = document.querySelectorAll('.tree-item');

    // 如果URL中有type参数，则根据参数设置初始选中状态
    if (contentType) {
        const targetTreeItem = document.querySelector(`.tree-item[data-tree="${contentType}"]`);
        if (targetTreeItem) {
            // 移除所有树形菜单项的选中状态
            treeItems.forEach(treeItem => treeItem.classList.remove('selected'));
            // 为目标菜单项添加选中状态
            targetTreeItem.classList.add('selected');

            // 更新当前菜单标题和数据
            if (contentType === 'exhibition') {
                document.querySelector('#current-menu .title').textContent = '馆办动态';
                currentDataType = 'exhibition';
                currentData = exhibitionData;
            } else if (contentType === 'inquiry') {
                document.querySelector('#current-menu .title').textContent = '业内动态';
                currentDataType = 'inquiry';
                currentData = inquiryData;
            }

            // 重新计算总页数
            currentPage = 1;
            totalPages = Math.ceil(currentData.length / pageSize);
            changePage(1);
        }
    }

    treeItems.forEach(item => {
        item.addEventListener('click', function (e) {
            // 移除所有树形菜单项的选中状态
            treeItems.forEach(treeItem => treeItem.classList.remove('selected'));
            // 为当前点击的菜单项添加选中状态
            this.classList.add('selected');

            // 根据点击的菜单项切换内容
            const treeType = this.getAttribute('data-tree');
            if (treeType === 'exhibition') {
                // 显示馆办动态内容
                document.querySelector('#current-menu .title').textContent = '馆办动态';
                currentDataType = 'exhibition';
                currentData = exhibitionData;
            } else if (treeType === 'inquiry') {
                // 显示业内动态内容
                document.querySelector('#current-menu .title').textContent = '业内动态';
                currentDataType = 'inquiry';
                currentData = inquiryData;
            }

            // 重新计算总页数并切换到第一页
            currentPage = 1;
            totalPages = Math.ceil(currentData.length / pageSize);
            changePage(1);
        });
    });

    // 分页控件事件处理
    document.querySelector('#prev-page').addEventListener('click', function () {
        changePage(currentPage - 1);
    });

    document.querySelector('#next-page').addEventListener('click', function () {
        changePage(currentPage + 1);
    });

    document.querySelector('#page-size').addEventListener('change', function () {
        changePageSize(this.value);
    });

    // 为页码输入框添加回车和失焦事件
    const pageInput = document.querySelector('#page-input');
    pageInput.addEventListener('keypress', function (e) {
        if (e.key === 'Enter') {
            const page = parseInt(this.value);
            if (!isNaN(page)) {
                changePage(page);
            } else {
                this.value = currentPage;
            }
        }
    });

    // 添加鼠标离开时触发页面翻页
    pageInput.addEventListener('blur', function () {
        const page = parseInt(this.value);
        if (!isNaN(page)) {
            changePage(page);
        } else {
            this.value = currentPage;
        }
    });


    // 清理了不再需要的点击事件处理代码

    // 移除了不再需要的轮播图相关功能
});